package YPTServerRegister

import (
	pb "git.oschina.net/YPTArch/ypt_service_discovery/etcd"
	"google.golang.org/grpc"
	"context"
	"fmt"
)

type CommonLease struct{  //etcd通用的一个过期设置
	TTL int64  //一定要比etcd key刷新时间长
	client *grpc.ClientConn
	id int64
}

func NewLease(client *grpc.ClientConn) *CommonLease{
	return &CommonLease{
		TTL : 20,
		client : client,
	}
}

func (c *CommonLease) GetCommonLease(){
}

func (c *CommonLease) GrantLease() (id int64,err error){
	lClient := pb.NewLeaseClient(c.client)
	res, err := lClient.LeaseGrant(context.Background(),&pb.LeaseGrantRequest{
		TTL : c.TTL,
		ID : 0,
	})
	c.id = res.ID
	return res.ID,err
}

func (c *CommonLease) GetLeaseInfo(){
	lClient := pb.NewLeaseClient(c.client)
	r ,_ :=lClient.LeaseTimeToLive(context.Background(),&pb.LeaseTimeToLiveRequest{
		ID : c.id,
		Keys:true,
	})
	fmt.Println("lease info",r)
}

/*
func (c *CommonLease) KeepAlive(id int64){
	lClient := pb.NewLeaseClient(c.client)

	aliveClient ,err := lClient.LeaseKeepAlive(context.Background())
	if err != nil {
		return
	}
	alive := make(chan struct{})

	go func() {
		for{
			msg ,err := aliveClient.Recv()
			fmt.Println("keep alive msg",msg)
			if err == io.EOF{
				close(alive)
				return
			}
			if err != nil{
				fmt.Println(err)
				return
			}
		}
	}()
	err = aliveClient.Send(&pb.LeaseKeepAliveRequest{
		ID : id,
	})
	aliveClient.CloseSend()
	if err != nil{
		fmt.Println(err)
		return
	}
	<-alive
}*/
